package com.example.service;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Service
@Slf4j
public class FieldMappingService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private Map<String, String> fieldMappings = new ConcurrentHashMap<>();

    @PostConstruct
    public void init() {
        loadFieldMappingsFromDatabase();
        log.info("字段映射服务初始化完成，共加载 {} 个映射", fieldMappings.size());
    }

    private void loadFieldMappingsFromDatabase() {
        try {
            String currentDatabase = jdbcTemplate.queryForObject("SELECT DATABASE()", String.class);

            String sql = """
            SELECT COLUMN_NAME, COLUMN_COMMENT 
            FROM INFORMATION_SCHEMA.COLUMNS 
            WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'dongtai'
            AND COLUMN_COMMENT IS NOT NULL AND COLUMN_COMMENT != '' AND TRIM(COLUMN_COMMENT) != ''
        """;

            List<Map<String, Object>> results = jdbcTemplate.queryForList(sql, currentDatabase);

            for (Map<String, Object> row : results) {
                String columnName = (String) row.get("COLUMN_NAME");
                String columnComment = (String) row.get("COLUMN_COMMENT");

                if (columnName != null && columnComment != null && !columnComment.trim().isEmpty()) {
                    String cleanComment = columnComment.trim();

                    // 存储多种格式的映射
                    fieldMappings.put(columnName.toUpperCase(), cleanComment);  // EPBP_SCJDDISHEN
                    fieldMappings.put(columnName.toLowerCase(), cleanComment);  // epbp_scjddishen

                    // 移除下划线的版本
                    String withoutUnderscore = columnName.replace("_", "").toLowerCase();
                    fieldMappings.put(withoutUnderscore, cleanComment);  // epbpscjddishen

                    // 驼峰命名版本（针对 EPBP 字段）
                    if (columnName.toUpperCase().startsWith("EPBP_")) {
                        String camelCase = convertToCamelCase(columnName);
                        fieldMappings.put(camelCase, cleanComment);  // epbpScjddishen
                    }
                }
            }

            log.info("从数据库加载了 {} 个字段映射", results.size());

        } catch (Exception e) {
            log.error("从数据库加载字段映射失败: {}", e.getMessage(), e);
        }
    }

    /**
     * 将下划线格式转换为驼峰命名
     * 例如：EPBP_SCJDDISHEN -> epbpScjddishen
     */
    private String convertToCamelCase(String fieldName) {
        if (fieldName == null || fieldName.isEmpty()) {
            return fieldName;
        }

        String[] parts = fieldName.toLowerCase().split("_");
        StringBuilder camelCase = new StringBuilder(parts[0]);

        for (int i = 1; i < parts.length; i++) {
            if (parts[i].length() > 0) {
                camelCase.append(Character.toUpperCase(parts[i].charAt(0)));
                if (parts[i].length() > 1) {
                    camelCase.append(parts[i].substring(1));
                }
            }
        }

        return camelCase.toString();
    }
    /**
     * 获取字段的中文名称
     */
    public String getChineseFieldName(String englishFieldName) {
        if (englishFieldName == null || englishFieldName.trim().isEmpty()) {
            return "";
        }

        String fieldName = englishFieldName.trim();

        // 按优先级依次尝试匹配：
        // 1. 精确匹配（保持原大小写）
        String chineseName = fieldMappings.get(fieldName);
        if (chineseName != null) {
            return chineseName;
        }

        // 2. 尝试小写匹配
        chineseName = fieldMappings.get(fieldName.toLowerCase());
        if (chineseName != null) {
            return chineseName;
        }

        // 3. 尝试大写匹配
        chineseName = fieldMappings.get(fieldName.toUpperCase());
        if (chineseName != null) {
            return chineseName;
        }

        // 如果都没找到，返回原字段名
        log.debug("未找到字段 '{}' 的中文映射，使用原名称", fieldName);
        return fieldName;
    }

    /**
     * 获取所有字段映射（只返回大写版本，避免重复）
     */
    public Map<String, String> getAllFieldMappings() {
        Map<String, String> result = new HashMap<>();
        for (Map.Entry<String, String> entry : fieldMappings.entrySet()) {
            String key = entry.getKey();
            // 只返回大写版本，避免重复
            if (key.equals(key.toUpperCase())) {
                result.put(key, entry.getValue());
            }
        }
        return result;
    }
}
